package com.xydtech.common.utils;

import com.itextpdf.text.Font;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

/**
 * 创建时间：2022/1/17 15:49
 * 项目名称：xydtech
 * @author JHON
 * @version 1.0
 * @since JDK 1.8.0_201
 * 文件名称：PdfReport
 * 类说明：pdf工具类
 */
public class PdfUtil {
    /**最大宽度*/
    private static int maxWidth = 520;

/**------------------------创建表格单元格的方法start----------------------------*/
    /**
     * 创建单元格(指定字体)
     * @param value
     * @param font
     * @return
     */
    public static PdfPCell createCell(String value, Font font) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }

    /**
     * 创建单元格（指定字体、水平..）
     * @param value
     * @param font
     * @param align
     * @return
     */
    public static PdfPCell createCell(String value, Font font, int align) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }

    /**
     * 创建单元格（指定字体、水平居..、单元格跨x列合并、设置单元格内边距）
     * @param value
     * @param font
     * @param align
     * @param colspan
     * @param boderFlag
     * @return
     */
    public static PdfPCell createCell(String value, Font font, int align, int colspan, boolean boderFlag) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setColspan(colspan);
        cell.setPhrase(new Phrase(value, font));
        cell.setPadding(3.0f);
        if (!boderFlag) {
            cell.setBorder(0);
            cell.setPaddingTop(5.0f);
            cell.setPaddingBottom(5.0f);
        } else if (boderFlag) {
            cell.setBorderWidthLeft(0.2f);
            cell.setBorderWidthRight(0.2f);
            cell.setBorderWidthTop(0.2f);
            cell.setBorderWidthBottom(0.2f);
            cell.setPaddingTop(4f);
            cell.setPaddingBottom(4f);
        }
        cell.getColumn().setLeading(0f, 1.5f);
        return cell;
    }

    /**
     * 创建单元格（指定字体、水平居..、单元格跨x列合并、设置单元格内边距）
     * @param value
     * @param font
     * @param align
     * @param colspan
     * @param borderWidth
     * @return
     */
    public static PdfPCell createCell(String value, Font font, int align, int colspan, float[] borderWidth) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setColspan(colspan);
        cell.setPhrase(new Phrase(value, font));
        cell.setPadding(3.0f);
        cell.setBorderWidthLeft(borderWidth[0]);
        cell.setBorderWidthRight(borderWidth[1]);
        cell.setBorderWidthTop(borderWidth[2]);
        cell.setBorderWidthBottom(borderWidth[3]);
        cell.setBorderColor(BaseColor.RED);
        cell.getColumn().setLeading(0f, 1.5f);
        return cell;
    }

    /**
     * 创建单元格（指定字体、水平..、边框宽度：0表示无边框、内边距）
     * @param value
     * @param font
     * @param align
     * @param borderWidth
     * @param paddingSize
     * @param flag
     * @return
     */
    public static PdfPCell createCell(String value, Font font, int align, float[] borderWidth, float[] paddingSize, boolean flag, BaseColor backgroundColor) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setPhrase(new Phrase(value, font));
        cell.setBorderWidthLeft(borderWidth[0]);
        cell.setBorderWidthRight(borderWidth[1]);
        cell.setBorderWidthTop(borderWidth[2]);
        cell.setBorderWidthBottom(borderWidth[3]);
        cell.setPaddingTop(paddingSize[0]);
        cell.setPaddingBottom(paddingSize[1]);
        if (flag) {
            cell.setColspan(2);
        }
        if (backgroundColor != null) {
            cell.setBackgroundColor(backgroundColor);
        }
        return cell;
    }
/**------------------------创建表格单元格的方法end----------------------------*/


/**--------------------------创建表格的方法start------------------- ---------*/
    /**
     * 创建默认列宽，指定列数、水平(居中、右、左)的表格
     * @param colNumber
     * @param align
     * @return
     */
    public static PdfPTable createTable(int colNumber, int align) {
        PdfPTable table = new PdfPTable(colNumber);
        try {
            table.setTotalWidth(maxWidth);
            table.setLockedWidth(true);
            table.setHorizontalAlignment(align);
            table.getDefaultCell().setBorder(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }

    /**
     * 创建指定列宽、列数的表格
     * @param widths
     * @return
     */
    public static PdfPTable createTable(float[] widths) {
        PdfPTable table = new PdfPTable(widths);
        try {
            table.setTotalWidth(maxWidth);
            table.setLockedWidth(true);
            table.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.getDefaultCell().setBorder(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return table;
    }

    /**--------------------------创建表格的方法end------------------- ---------*/

    /**
     *pdf转图片加水印
     * @Title: pdfToImgAddWaterMask
     * @param pdfFile
     * @param imgPath
     * @param waterMask
     * @param del 是否删除PDF文件,1是2否
     * @return void
     * @exception
     * @author JHON
     * @Date 2022/9/27 21:20
     **/
    public static void pdfToImgAddWaterMask(String pdfFile, String imgPath, String waterMask,int del) throws IOException {
        // 根据指定文件创建输入流
        File files = new File(pdfFile);
        PDDocument pd = PDDocument.load(files);
        PDFRenderer pdfRenderer = new PDFRenderer(pd);
        BufferedImage combined = null;
        for (int page = 0; page < pd.getNumberOfPages(); ++page) {
            BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 170, ImageType.RGB);
            if (page == 0) {
                combined = bim;
            } else {
                combined = merge(combined, bim);
            }
        }

        //如果图片不为空
        if (combined != null) {
            //添加水印
            combined = addWaterMask(combined, waterMask);

            ImageIO.write(combined, "png", new File(imgPath));
        }
        pd.close();
        if (del==1) {
            files.delete();
        }
    }

    /**
     * 添加水印
     * @param image 图片
     * @param maskStr 水印字符串
     * @return
     */
    private static BufferedImage addWaterMask(BufferedImage image, String maskStr) {

        int imgHeight = image.getHeight();
        int imgWidth = image.getWidth();

        //获取 Graphics2D 对象
        Graphics2D g = image.createGraphics();
        //设置绘图区域
        g.drawImage(image, imgWidth, imgHeight, null);
        //设置字体
        int timeFontSize = 50;
        java.awt.Font font = new java.awt.Font("Microsoft YaHei", java.awt.Font.PLAIN, timeFontSize);
        g.setFont(font);
        // 根据图片的背景设置水印颜色
        g.setColor(Color.GRAY);
        //设置透明
        AlphaComposite alphaComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.35f);
        g.setComposite(alphaComposite);
        //设置抗锯齿
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        //设置偏转
        g.rotate(-Math.PI / 5, imgWidth / 2, imgHeight / 2);
        for (int x = -imgHeight; x < imgHeight; x += 600) {
            for (int y = -imgHeight; y < imgHeight; y += 300) {
                g.drawString(maskStr + " " + DateUtils.getDate(), x, y);
            }
        }

        g.dispose();

        return image;
    }

    /**
     * 合并图片
     * @param image1
     * @param image2
     * @return
     */
    private static BufferedImage merge(BufferedImage image1, BufferedImage image2) {
        BufferedImage combined = new BufferedImage(
                image1.getWidth(),
                image1.getHeight() + image2.getHeight(),
                BufferedImage.TYPE_INT_RGB);

        Graphics g = combined.getGraphics();
        g.drawImage(image1, 0, 0, null);
        g.drawImage(image2, 0, image1.getHeight(), null);
        g.dispose();
        return combined;
    }

    /**
     * 截取pdfFile的第from页至第end页，组成一个新的文件名
     * @param respdfFile  需要分割的PDF
     * @param savepath  新PDF
     */
    public static void splitPDFFile(String respdfFile,
                                    String savepath) {
        Document document = null;
        PdfCopy copy = null;

        try {
            PdfReader reader = new PdfReader(respdfFile);
            int n = reader.getNumberOfPages();
            //起始页
            int from = 2;
            //结束页
            int end = n;
            ArrayList<String> savepaths = new ArrayList<String>();
            String staticpath = respdfFile.substring(0, respdfFile.lastIndexOf("\\") + 1);
            //String savepath = staticpath+ newFile;
            savepaths.add(savepath);
            document = new Document(reader.getPageSize(1));
            copy = new PdfCopy(document, new FileOutputStream(savepaths.get(0)));
            document.open();
            for (int j = from; j < end; j++) {
                document.newPage();
                PdfImportedPage page = copy.getImportedPage(reader, j);
                copy.addPage(page);
            }
            document.close();
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        String respdfFile = "D:\\report\\2022121209020200000276-tax.pdf";
        String savepath = "D:\\report\\2022121209020200000276-tax2.pdf";

        splitPDFFile(respdfFile, savepath);
    }
}

